package com.itbour.web.action.trade;

import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.util.EntityUtils;
import org.apache.struts2.ServletActionContext;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.itbour.com.page.Page;
import com.itbour.common.base.BaseAction;
import com.itbour.common.util.StringUtils;
import com.itbour.dto.com.UserInfoDto;
import com.itbour.dto.trade.ExpTrackInfoDto;
import com.itbour.dto.trade.ExpressComInfoDto;
import com.itbour.dto.trade.OrdDtlPrtImgInfoDto;
import com.itbour.dto.trade.OrderInfoDto;
import com.itbour.dto.trade.OrderDetailInfoDto;
import com.itbour.dto.trade.PartnerInfoDto;
import com.itbour.dto.trade.StateHisInfoDto;
import com.itbour.service.trade.OrdersService;
import com.opensymphony.xwork2.ActionContext;
import com.qiniu.http.CusHttpUtils;
import com.qiniu.util.HttpRequest;

import freemarker.template.utility.StringUtil;

/**
 * copyright Itbour team 2016
 * 
 * @author xc
 */

public class GetOrdersWebAction extends BaseAction {

	private static final long serialVersionUID = 1L;

	private OrdersService ordersService;
	
	// [订单]
	private HashMap<String, Object> ordersMapResult = new HashMap<String, Object>();//[分页]订单信息列表
	private HashMap<String, Object> detailsMapResult = new HashMap<String, Object>();//[分页]订单明细信息列表
	private List<OrderInfoDto> ordersInfoList;// 订单信息列表
	private List<OrderDetailInfoDto> detailsInfoList;// 订单明细信息列表
	private OrderInfoDto orderInfo;// 更新用
	private OrderDetailInfoDto detailInfo;// 更新用
	private String withBleed;// 是否带出血
	private String zoom;// 放大倍率
	private String orderId;// 订单id
	private String detailId;// 订单明细id
	private String printImgsInfo;// 印刷用图像文件:[{detailId:1,printImgs:['xxx',...]},...]

	private String findPubFlg;// 检索条件[发布状态]
	private String findOrderId;// 检索条件[订单ID]
	private String findOrderNo;// 检索条件[订单编号]
	private String findPayOrderNo;// 检索条件[支付订单编号]
	private String findType;// 检索条件[订单分类]
	private String findState;// 检索条件[订单状态]
	private String findPartner;// 检索条件[合作方]
	private String findPayPf;// 检索条件[支付平台]
	private String findInvId;// 检索条件[发票id]
	private String findMobile;// 检索条件[用户手机]
	private String findDateStart;// 检索条件[时间范围(起始)]
	private String findDateEnd;// 检索条件[时间范围(截止)]
	private String ids;// 通用ids[逗号连接]
	private String order;// 显示顺序
	private String findUserId;// 用户Id
	
	private List<PartnerInfoDto> partnerComboList;// 合作方
	
	private StateHisInfoDto stateHisInfo;// 订单状态历史
	
	
	// 分页获取订单信息
	public String getOrdersInfoPg() throws Exception {
		// 用户信息
		Map<String, Object> session = ActionContext.getContext().getSession();
    	UserInfoDto user = (UserInfoDto)session.get("user");
    	if (user!=null && user.getUser_id() !=null){
			HttpServletRequest request = ServletActionContext.getRequest();
			String pageNumber = request.getParameter("page");
			String pageSize = request.getParameter("rows");
			
			Map<String, Object> param = new HashMap<String, Object>();
			if (StringUtils.isNotEmpty(findOrderId)) {
				param.put("order_id", findOrderId);
			}
			if (StringUtils.isNotEmpty(findOrderNo)) {
				param.put("order_no", "%"+findOrderNo+"%");
			}
			if (StringUtils.isNotEmpty(findPayOrderNo)) {
				param.put("pay_order_no", "%"+findPayOrderNo+"%");
			}
			if (StringUtils.isNotEmpty(findInvId)) {
				param.put("inv_id", findInvId);
			}
			if (StringUtils.isNotEmpty(findMobile)) {
				param.put("mobile", findMobile);
			}
			if (StringUtils.isNotBlank(findType)) {
				param.put("type", findType);
			}
			if (StringUtils.isNotEmpty(findState)) {
				if (Integer.valueOf(findState) == 101){ // 如果等于
					param.put("state","11,20,30,40");
				} else {
					param.put("state", findState);
				}
			}
			if (StringUtils.isNotEmpty(findPartner)) {
				param.put("partner_id", findPartner);
			}
			if (StringUtils.isNotEmpty(findPayPf)) {// 支付平台
				param.put("pay_platform", findPayPf);
			}
	//		if (StringUtils.isNotBlank(findPubFlg)) {
	//			param.put("publish", findItemState);
	//		}
			if (StringUtils.isNotBlank(findDateStart)) {
				param.put("crtDateStart", findDateStart);
			}
			if (StringUtils.isNotBlank(findDateEnd)) {
				param.put("crtDateEnd", findDateEnd);
			}
			if (StringUtils.isNotEmpty(findUserId)){
				param.put("user_id", findUserId);
			}
			Page page = ordersService.ordersPgQuery(param,
					Integer.parseInt(pageNumber),
					Integer.parseInt(pageSize));
			HashMap<String, Object> resMap = new HashMap<String, Object>();
			resMap.put("total", page.getTotalCount());
			resMap.put("rows", page.getResult());
			//writeJSON(resMap);
			ordersMapResult = resMap;
    	}
		return SUCCESS;
	}
	
	// 分页获取订单信息(酒单网用)
	public String getOrderInfo2Pg() throws Exception {
		// 用户信息
		Map<String, Object> session = ActionContext.getContext().getSession();
    	UserInfoDto user = (UserInfoDto)session.get("user");
    	
		HttpServletRequest request = ServletActionContext.getRequest();
		String pageNumber = request.getParameter("page");
		String pageSize = request.getParameter("rows");
		
		Map<String, Object> param = new HashMap<String, Object>();
		// 酒单网
		param.put("partner_id", 3);
		
		if (StringUtils.isNotEmpty(findOrderNo)) {
			param.put("order_no", "%"+findOrderNo+"%");
		}
		if (StringUtils.isNotEmpty(findMobile)) {
			param.put("mobile", findMobile);
		}
		if (StringUtils.isNotEmpty(findState)) {
			param.put("state", findState);
		}
		if (StringUtils.isNotBlank(findDateStart)) {
			param.put("crtDateStart", findDateStart);
		}
		if (StringUtils.isNotBlank(findDateEnd)) {
			param.put("crtDateEnd", findDateEnd);
		}
		Page page = ordersService.ordersPgQuery(param,
				Integer.parseInt(pageNumber),
				Integer.parseInt(pageSize));
		HashMap<String, Object> resMap = new HashMap<String, Object>();
		resMap.put("total", page.getTotalCount());
		resMap.put("rows", page.getResult());
		//writeJSON(resMap);
		ordersMapResult = resMap;
		return SUCCESS;
	}
	
	// 分页获取订单明细信息
	public String getDetailsInfoPg() throws Exception {
		// 用户信息
		Map<String, Object> session = ActionContext.getContext().getSession();
    	UserInfoDto user = (UserInfoDto)session.get("user");
    	
		HttpServletRequest request = ServletActionContext.getRequest();
		String pageNumber = request.getParameter("page");
		String pageSize = request.getParameter("rows");
		
		Map<String, Object> param = new HashMap<String, Object>();
		if (StringUtils.isNotEmpty(findOrderNo)) {
			param.put("order_no", "%"+findOrderNo+"%");
		}
		if (StringUtils.isNotEmpty(findOrderId)) {
			param.put("order_id", findOrderId);
		}
		if (StringUtils.isNotEmpty(findState)) {
			param.put("state", findState);
		}
//			if (StringUtils.isNotBlank(findPubFlg)) {
//				param.put("publish", findItemState);
//			}
		Page page = ordersService.detailsPgQuery(param,
				Integer.parseInt(pageNumber),
				Integer.parseInt(pageSize));
		HashMap<String, Object> resMap = new HashMap<String, Object>();
		resMap.put("total", page.getTotalCount());
		resMap.put("rows", page.getResult());
		//writeJSON(resMap);
		detailsMapResult = resMap;
		return SUCCESS;
	}
	
	// 获取订单信息列表
	public String getOrdersInfoLst() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		Map<String, Object> param = new HashMap<String, Object>();
		String id = request.getParameter("order_id");
		if (StringUtils.isNotEmpty(id)) {
			param.put("order_id", id);
		}
		ordersInfoList = ordersService.selectOrdersInfo(param);
		return SUCCESS;
	}
	
	// 获取订单明细信息列表
	public String getDetailsInfoLst() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		Map<String, Object> param = new HashMap<String, Object>();
		String oid = request.getParameter("order_id");
		String did = request.getParameter("detail_id");
		if (StringUtils.isNotEmpty(oid)) {
			param.put("order_id", oid);
		}
		if (StringUtils.isNotEmpty(did)) {
			param.put("detail_id", did);
		}
		detailsInfoList = ordersService.selectDetailsInfo(param);
		return SUCCESS;
	}

	// 删除订单信息
	public void delOrder() throws Exception {
		ordersService.delOrder(ids);
		this.writeJSON("ok");
	}
	// 删除订单明细信息
	public void delDetail() throws Exception {
		ordersService.delDetail(ids);
		this.writeJSON("ok");
	}
	
	// 更新订单信息
	public void updOrder() throws Exception {
		if (orderInfo != null && 
			((orderInfo.getOrder_id() != null && orderInfo.getOrder_id()>0) || StringUtils.isNotBlank(orderInfo.getIds()))) {
			Map<String, Object> session = ActionContext.getContext().getSession();
	    	UserInfoDto user = (UserInfoDto)session.get("user");
	    	
	    	Map<String, Object> param = new HashMap<String, Object>();
	    	if(orderInfo.getOrder_id() != null && orderInfo.getOrder_id()>0){
		    	param.put("order_id", orderInfo.getOrder_id());
	    	}
	    	if(StringUtils.isNotBlank(orderInfo.getIds())){
	    		param.put("ids", StringUtils.listToString2(StringUtils.stringToList2(orderInfo.getIds())));
	    	}
	    	if(user != null) {
	    		param.put("update_by", user.getUser_id());
	    	}
	    	
	    	if(orderInfo.getPartner_id() != null ) {
	    		param.put("partner_id", orderInfo.getPartner_id());
	    	}
	    	if(orderInfo.getPay_platform() != null ) {
	    		param.put("pay_platform", orderInfo.getPay_platform());
	    	}
	    	if(orderInfo.getState() != null && orderInfo.getState()>0) {
	    		param.put("state", orderInfo.getState());
	    	}
	    	if(orderInfo.getTotal_fee() != null) {
	    		param.put("total_fee", orderInfo.getTotal_fee());
	    	}
	    	if(orderInfo.getAddr_id() != null) {
	    		param.put("addr_id", orderInfo.getAddr_id());
	    	}
	    	if(orderInfo.getUser_id() != null) {
	    		param.put("user_id", orderInfo.getUser_id());
	    	}
	    	if(orderInfo.getType() != null && orderInfo.getType()>0) {
	    		param.put("type", orderInfo.getType());
	    	}
	    	if(orderInfo.getDesc() != null) {
	    		param.put("desc", orderInfo.getDesc());
	    	}
	    	ordersService.updOrder(param);
		}
		this.writeJSON("ok");
	}
	
	// 更新订单明细信息
	public void updDetail() throws Exception {
		if (detailInfo != null && 
			((detailInfo.getDetail_id() != null && detailInfo.getDetail_id()>0) || StringUtils.isNotBlank(detailInfo.getIds()))) {
			Map<String, Object> session = ActionContext.getContext().getSession();
	    	UserInfoDto user = (UserInfoDto)session.get("user");
	    	
	    	Map<String, Object> param = new HashMap<String, Object>();
	    	if(detailInfo.getOrder_id() != null && detailInfo.getOrder_id()>0){
		    	param.put("order_id", detailInfo.getOrder_id());
	    	}
	    	if(detailInfo.getDetail_id() != null && detailInfo.getDetail_id()>0){
		    	param.put("detail_id", detailInfo.getDetail_id());
	    	}
	    	if(StringUtils.isNotBlank(detailInfo.getIds())){
	    		param.put("ids", StringUtils.listToString2(StringUtils.stringToList2(detailInfo.getIds())));
	    	}
	    	if(user != null) {
	    		param.put("update_by", user.getUser_id());
	    	}
	    	
	    	if(detailInfo.getState() != null && detailInfo.getState()>0) {
	    		param.put("state", detailInfo.getState());
	    	}
	    	if(detailInfo.getDesc() != null) {
	    		param.put("desc", detailInfo.getDesc());
	    	}
	    	if(detailInfo.getExpress() != null) {
	    		param.put("express", detailInfo.getExpress());
	    	}
	    	if(detailInfo.getTracking_no() != null) {
	    		param.put("tracking_no", detailInfo.getTracking_no());
	    	}
	    	if(detailInfo.getExc_id()!=null){//快递主键
	    		param.put("exc_id",detailInfo.getExc_id());
	    	}
	    	
	    	ordersService.updDetail(param);
		}
		this.writeJSON("ok");
	}

	// 获取合作方
	public String getPartnerForCombo() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		String flg = request.getParameter("blkFlg");
		Map<String, Object> param = new HashMap<String, Object>();
		partnerComboList = ordersService.selectPartnerInfo(param);
		if(partnerComboList != null && partnerComboList.size()>0){
			// 添加空白项目
			if("1".equals(flg)){
				PartnerInfoDto blankItem = new PartnerInfoDto();
				blankItem.setId(0L);
				blankItem.setName("[不限]");
				partnerComboList.add(0, blankItem);
			}
		}
		return SUCCESS;
	}
	
	// 订单状态历史
	public void addStateHis() throws Exception {
		if (stateHisInfo != null) {
			Map<String, Object> session = ActionContext.getContext().getSession();
	    	UserInfoDto user = (UserInfoDto)session.get("user");
	    	if (user != null) {
	    		stateHisInfo.setUpdate_by(user.getUser_id().toString());
	    	}
	    	ordersService.addStateHis(stateHisInfo);
		}
		this.writeJSON("ok");
	}
	
	// 通知用户
	public void notifyUser() throws Exception {
		Map<String, Object> session = ActionContext.getContext().getSession();
    	UserInfoDto user = (UserInfoDto)session.get("user");
		if (user!=null && orderInfo != null 
			&& orderInfo.getOrder_id() != null && orderInfo.getOrder_id()>0
			&& orderInfo.getState() != null && orderInfo.getState()>0
			&& orderInfo.getUser_id() != null && orderInfo.getUser_id()>0) {
	    	
	    	Map<String, Object> param = new HashMap<String, Object>();
	    	if(orderInfo.getState()==30) {
	    		// 默认消息ID: 58[发货用]
	    		param.put("notify_id", 58);
	    	} else {
	    		// TODO
	    		param.put("notify_id", 58);
	    	}
	    	param.put("state", 10);// 10:新建
	    	param.put("user_id", orderInfo.getUser_id());
	    	param.put("update_by", user.getUser_id());
	    	
	    	ordersService.addNotifyUserRecd(param);
	    	this.writeJSON("ok");
		} else {
			this.writeJSON("ng");
		}
	}
	
	/**导出订单中的用户文档信息
	 */
	public void downOdrUserDocInfo() throws Exception {
//		String API_SVR = "http://120.27.141.121:3000";
		String API_SVR = "https://api.itbour.com";
		//API_SVR = "http://192.168.31.252:3000";// for Debug
		//API_SVR = "http://test.itbour.com:3000";// for Local Debug
		
		HttpServletRequest request = ServletActionContext.getRequest();
		Integer orderId = Integer.parseInt(request.getParameter("orderId"));
		
		StringBuilder sb = new StringBuilder();
		String SEP = ",";
		Date date = new Date();
		SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat sim2 = new SimpleDateFormat("yyyyMMddHHmmss");
		String date1 = sim.format(date);
		String date2 = sim2.format(date);
	    
		sb.append("订单ID:").append(SEP).append(orderId).append("\n");
		sb.append("用户文档信息:").append(SEP).append(date1).append("\n");
		
		// 获取文档
		String retStr=HttpRequest.sendGet(API_SVR+"/v5/api4back/getOrderUserDocText",
				"orderId="+orderId);
	    JSONObject retObj=JSONObject.fromObject(retStr);
	    String suc = retObj.get("success").toString();
	    JSONObject retData=(JSONObject) retObj.get("data");
		
		if("1".equals(suc) && retData!=null){
			JSONArray jsonArray = JSONArray.fromObject(retData.get("list"));
			// 循环各文档
			for (int i = 0; i < jsonArray.size(); i++) {
				JSONObject docInfo = (JSONObject) jsonArray.get(i);
				sb.append("\n");
				
				// 标题
				List<String> titleList = (List<String>) docInfo.get("titles");
				sb=sb.append("子订单ID:").append(SEP)
						.append("商品ID").append(SEP)
						.append("用户文档ID");
				for (int n = 0; n < titleList.size(); n++) {
					sb=sb.append(SEP).append(titleList.get(n));
				}
				sb.append("\n");
				// 内容
				List<String> textList = (List<String>) docInfo.get("texts");
				sb=sb.append("\""+docInfo.get("orderDetailId")+"\"")
						.append(SEP).append("\""+docInfo.get("itemId")+"\"")
						.append(SEP).append("\""+docInfo.get("userDocId")+"\"");
				for (int m = 0; m < textList.size(); m++) {
					sb=sb.append(SEP).append("\"" + Null2Str(textList.get(m)) + "\"");
				}
				sb.append("\n");
			}
			
			String fileName = "ODR_"+orderId+"_UserDocInfo_" + date2 + ".csv";
	        String output = sb.toString();
	        HttpServletResponse response = ServletActionContext.getResponse();
	        response.addHeader("Content-Disposition", "attachment; filename="+fileName); 
	        response.setContentType("application/octet-stream"); 
	        response.setCharacterEncoding("UTF8"); 
	        response.getWriter().write(output); 
	        response.flushBuffer();
	        
		} else {
			// TODO
		}
	}
	
	/**导出订单信息
	 */
	public void downOrderInfo() throws Exception{
		StringBuilder sb = new StringBuilder();
		String SEP = ",";
		
		Date date = new Date();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat format2 = new SimpleDateFormat("yyyyMMddHHmmss");
		String dataStr = format.format(date);
		String dataStr2 = format2.format(date);
		
		sb.append("示界港订单详情:").append(SEP).append(dataStr).append("\n");
		
		sb.append("订单编号")
		.append(SEP).append("订单明细编号")
		.append(SEP).append("状态")
		//.append(SEP).append("合作方")// TODO 暂时屏蔽
		.append(SEP).append("商品编号")
		.append(SEP).append("商品名称")
		.append(SEP).append("套餐名称")
		.append(SEP).append("套餐信息")
		.append(SEP).append("用户ID")
		.append(SEP).append("用户手机号")
		.append(SEP).append("商品数量")
		.append(SEP).append("输出尺寸(w*h)")
		.append(SEP).append("出血")
		.append(SEP).append("分辨率")
		.append(SEP).append("印刷文件")
		.append(SEP).append("收件人")
		.append(SEP).append("联系电话")
		.append(SEP).append("联系电话2")
		.append(SEP).append("配送运费")
		.append(SEP).append("收件地址")
		.append(SEP).append("订单金额(元)")
		.append(SEP).append("创建时间")
		.append("\n");
		
		
		if(StringUtils.isNotEmpty(orderId) && StringUtils.isNotEmpty(printImgsInfo)){
			List<String> ids=StringUtils.stringToList(orderId);
			JSONArray json=JSONArray.fromObject(printImgsInfo);
			for (int k = 0; k < ids.size(); k++) {
				String id=ids.get(k);
				
				// 获取订单信息
				Map<String, Object> param = new HashMap<String, Object>();
				param.put("order_id", id);
				List<OrderInfoDto> oInfoLst = ordersService.selectOrdersInfo(param);
				if(oInfoLst!=null && oInfoLst.size()>0) {
					OrderInfoDto baseInfo = oInfoLst.get(0);
					List<OrderDetailInfoDto> dInfoLst = ordersService.selectDetailsInfo(param);
					if(dInfoLst!=null && dInfoLst.size()>0){
						for(int i=0; i<dInfoLst.size(); i++) {
							OrderDetailInfoDto dtlInfo = dInfoLst.get(i);
							
							// 拼接图像地址信息
							String imgInfo = "";
							if (!json.isEmpty()){
								JSONObject jsons=(JSONObject) json.get(k);
								// 解析下载用图片信息
								Gson gson = new Gson();
								List<OrdDtlPrtImgInfoDto> prtImgInfoLst = gson.fromJson(jsons.get("list").toString(),
										new TypeToken<List<OrdDtlPrtImgInfoDto>>(){}.getType());
								imgInfo = "\"";
								if(prtImgInfoLst!=null && prtImgInfoLst.size()>0){
									for(int n=0; n<prtImgInfoLst.size(); n++){
										OrdDtlPrtImgInfoDto prtImgInfo = prtImgInfoLst.get(n);
										// 匹配明细项id
										if(prtImgInfo.getDetailId()!=null && dtlInfo.getDetail_id()!=null
												&& prtImgInfo.getDetailId().equals(dtlInfo.getDetail_id())) {
											if(prtImgInfo.getImages()!=null && prtImgInfo.getImages().size()>0){
												for(int m=0; m<prtImgInfo.getImages().size(); m++){
													if(m>0) {
														imgInfo += "\n";
													}
													imgInfo += Null2Str(prtImgInfo.getImages().get(m));
													
													// 不需要出血
	//												if(withBleed!=null && zoom!=null && StringUtils.isEqual("0", withBleed)) {
	//													BigDecimal dZoom = new BigDecimal(zoom);
	//													BigDecimal dW = dZoom.multiply(BigDecimal.valueOf(dtlInfo.getDpi()))
	//															.multiply(BigDecimal.valueOf(dtlInfo.getPrint_w()))
	//															.divide(BigDecimal.valueOf(25.4),0,BigDecimal.ROUND_CEILING);
	//													BigDecimal dH = dZoom.multiply(BigDecimal.valueOf(dtlInfo.getDpi()))
	//															.multiply(BigDecimal.valueOf(dtlInfo.getPrint_h()))
	//															.divide(BigDecimal.valueOf(25.4),0,BigDecimal.ROUND_CEILING);
	//													String ossParam = "?x-oss-process=image/crop,x_0,y_0,"+
	//															"w_"+dW.longValue()+",h_"+dH.longValue()+",g_center";
	//													imgInfo += ossParam;
	//												}
												}
											}
											break;
										}
									}
								}
								imgInfo += "\"";
							}
							
							// 订单状态
							String stateNm = "未知";
							switch(baseInfo.getState().intValue()) {
								case 10: stateNm="待支付"; break;
								case 11: stateNm="已支付"; break;
								case 12: stateNm="支付失败"; break;
								case 20: stateNm="制作中"; break;
								case 30: stateNm="配送中"; break;
								case 40: stateNm="完成"; break;
								case 50: stateNm="取消"; break;
							}
							
							// 配送方式
							String mailType = "未知";
							switch(baseInfo.getExpress_type().intValue()) {
								case 10: mailType= "已付"; break;
								case 20: mailType= "运费到付"; break;
							}
				
							// 订单金额
							double fee = baseInfo.getTotal_fee();
							if (fee>0){
								fee = fee/100;
							}
							
							
							// 收件详细地址
							String addr = "";
							if(Null2Str(baseInfo.getAddr_prov()).equals(Null2Str(baseInfo.getAddr_city()))) {// 北京，天津等
								addr = Null2Str(baseInfo.getAddr_city());
							} else {
								addr = Null2Str(baseInfo.getAddr_prov()).concat(Null2Str(baseInfo.getAddr_city()));
							}
							addr = addr.concat(Null2Str(baseInfo.getAddr_dist()))
									.concat(" ")
									.concat(Null2Str(baseInfo.getAddr_detail()))
									.replace("\"","");// 去掉双引号
							
							// 拼接一条明细行数据
							sb.append( "\""+Null2Str(baseInfo.getOrder_no())+"\"" )
							.append(SEP).append( "\""+Null2Str(dtlInfo.getDetail_no())+"\"" )
							.append(SEP).append( "\""+stateNm+"\"" )
							//.append(SEP).append( "\""+Null2Str(baseInfo.getPartner_name())+"\"" )
							.append(SEP).append( "\""+Null2Str(dtlInfo.getItem_no())+"\"" )
							.append(SEP).append( "\""+Null2Str(dtlInfo.getItem_name())+"\"" )
							.append(SEP).append( "\""+Null2Str(dtlInfo.getPp_name())+"\"" )
							.append(SEP).append( "\""+Null2Str(dtlInfo.getPp_desc())+"\"" )
							.append(SEP).append( "\""+Null2Str(baseInfo.getUser_id())+"\"" )
							.append(SEP).append( "\""+Null2Str(baseInfo.getMobile())+"\"" )
							.append(SEP).append( Null2Str(dtlInfo.getQty())+Null2Str(dtlInfo.getUnit()) )
							.append(SEP).append( Null2Str(dtlInfo.getPrint_w())+Null2Str(dtlInfo.getPrint_unit())+
									"*"+Null2Str(dtlInfo.getPrint_h())+Null2Str(dtlInfo.getPrint_unit()) )
							.append(SEP).append( Null2Str(dtlInfo.getPrint_bleed())+Null2Str(dtlInfo.getPrint_unit()) )
							.append(SEP).append( Null2Str(dtlInfo.getDpi())+"dpi" )
							.append(SEP).append(imgInfo)
							.append(SEP).append( "\""+Null2Str(baseInfo.getAddr_name())+"\"" )// 收件人
							.append(SEP).append( Null2Str(baseInfo.getAddr_mobile()) )
							.append(SEP).append( Null2Str(baseInfo.getAddr_tel()) )
							.append(SEP).append( "\""+mailType+"\"" )
							.append(SEP).append( "\""+addr+"\"" )
							.append(SEP).append( Null2Str(fee))
							.append(SEP).append( Null2Str(baseInfo.getCreate_time()) )
							.append("\n");
						}
					}
				}
		  }
		} else {
			sb.append("未获取到订单信息！\n");
		}
		String fileName = "ITB_ORDER_INFO_"+dataStr2+".csv";
        String output = sb.toString();
        HttpServletResponse response = ServletActionContext.getResponse();
        response.addHeader("Content-Disposition", "attachment; filename="+fileName); 
        response.setContentType("application/octet-stream"); 
        response.setCharacterEncoding("UTF8"); 
        response.getWriter().write(output); 
        response.flushBuffer();
	}
	
	
	
	
	/**获取快递分类
	 * @return ExpressComInfoDto 快递分类表
	 */
	private List<ExpressComInfoDto> listExpC;
	public String getExpClassificationInfo(){
		Map<String, Object> session = ActionContext.getContext().getSession();
    	UserInfoDto user = (UserInfoDto)session.get("user");
		if (user!=null && user.getUser_id()!=null) {//用户身份判断
			Map<String, Object> parm =new HashMap<String, Object>();
			ExpressComInfoDto expCom = new ExpressComInfoDto();
			long st = 0;
			expCom.setExc_id(st);
			expCom.setName("不限");
			expCom.setCd("unli");
			listExpC = ordersService.getExpComInfo(parm);
			listExpC.add(expCom);
			Collections.sort(listExpC);
		}
		return SUCCESS;
	}
	
	/**
	 * 更新订单物流信息
	 */
	public void updExpInfoData() throws Exception{
		Map<String, Object> session = ActionContext.getContext().getSession();
		UserInfoDto user = (UserInfoDto)session.get("user");
		if (user!=null && user.getUser_id()!=null) {//
			Map<String, Object> parm =new HashMap<String, Object>();
			HttpServletRequest request = ServletActionContext.getRequest();
			String number = request.getParameter("number");
			String type = request.getParameter("type");
			String ex_id =request.getParameter("ex_id");
			Map<String, String> headers = new HashMap<String, String>();
		    //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
		    headers.put("Authorization", "APPCODE " + appcode);
		    Map<String, String> querys = new HashMap<String, String>();
		    querys.put(expNum, number);//455851390017
		    if (type==null || "".equals(type)){
		    	querys.put("type", "auto");
		    } else {
		    	querys.put("type", type);
		    }
		    int ret = 1;
		    try{
		    	HttpResponse response = CusHttpUtils.doGet(host, path, method, headers, querys);
		    	StatusLine s = response.getStatusLine();
		    	if (s.getStatusCode() == 200){
			    	JSONObject json = JSONObject.fromObject(EntityUtils.toString(response.getEntity()));
			    	JSONObject result = (JSONObject) json.get("result");
			    	if (result != null){
				    	String deliveryStats = result.get("deliverystatus").toString();// 第二份API的state状态:1.在途中 2.正在派件 3.已签收 4.派送失败
					    parm.put("state",Integer.parseInt(deliveryStats)+1);
					    parm.put("data", json.toString().replace("&nbsp;"," "));
					    parm.put("ex_id",ex_id);
					    parm.put("update_by",user.getUser_id());
					    boolean b = ordersService.updExpInfoData(parm);
					    if (b){ret = 1;} else {ret = 2;}
			    	} else {ret = 3;}
		    	} else {ret = 4 ;}
		    }catch(Exception e){
		    	ret = 2;//定义出错返回2
		    	System.out.println(e.getMessage());
		    }
			if (ret == 1) {
				this.writeJSON("ok");
			} else if (ret == 2){
				this.writeJSON("no");
			} else if (ret == 3){
				this.writeJSON("null");
			} else if (ret == 4){
				this.writeJSON("noVail");
			}
		}
	}
	
	private Map<String, Object> expTracInfo = new HashMap<String, Object>();
	private String findNum;
	private String findExpType;
	private String findExpState;
	
	/**
	 *  查看物流列表
	 */
	public String getLogisticsInfo() throws Exception{
		Map<String, Object> session = ActionContext.getContext().getSession();
		UserInfoDto user =(UserInfoDto)session.get("user");
		if (user != null && user.getUser_id() != null){
			Map<String, Object> parm = new HashMap<String, Object>();
			HttpServletRequest request =ServletActionContext.getRequest();
			String pageNum = request.getParameter("page");
			String pageSize = request.getParameter("rows");// 条数
			if (StringUtils.isNotEmpty(findNum)){
				parm.put("ex_tracking_no",findNum);
			}
			if (StringUtils.isNotEmpty(findExpType) && Integer.parseInt(findExpType)!=0){// 物流类型
				parm.put("exc_id",findExpType);
			}
			if (StringUtils.isNotEmpty(findExpState)){
				parm.put("state",findExpState);
			}
			
			if (StringUtils.isNotEmpty(findNum) && findExpType != null && Integer.parseInt(findExpType)>0){
				Map<String, Object> map =new HashMap<String, Object>();
				map.put("ex_tracking_no",findNum);
				List<ExpTrackInfoDto> expT = ordersService.getExpTrackInfo(map);// 获取单个本地物流信息
				if (expT.size()<=0){
					Map<String, String> headers = new HashMap<String, String>();
					headers.put("Authorization", "APPCODE " + appcode);
					Map<String, String> querys = new HashMap<String, String>();
					List<ExpressComInfoDto> list = ordersService.getExpComInfo(parm);
					for (ExpressComInfoDto expressComInfoDto : list) {
						querys.put("type", expressComInfoDto.getCd());
					}
//					if (){
//					} else {
//						querys.put("type","auto");
//					}
					querys.put(expNum, findNum);// 订单号
					
					HttpResponse response = CusHttpUtils.doGet(host, path, method, headers, querys);// {"status":"205","msg":"没有信息","result":""}
			    	JSONObject json = JSONObject.fromObject(EntityUtils.toString(response.getEntity()));
			    	Integer status = Integer.parseInt(json.get("status").toString());
			    	if (status.equals(203) || status.equals(201) || status.equals(202)
			    			|| status.equals(204) || status.equals(205) || status.equals(206)) {// 表示没有信息
			    		System.out.println("是新物流单号 暂无信息 不需要更新");
			    	} else {
			    		JSONObject result = (JSONObject) json.get("result");
			    		String deliveryStats = result.get("deliverystatus").toString();
			    		Map<String, Object> temp =new HashMap<String, Object>();
			    		if(Integer.parseInt(deliveryStats) >= 0){
			    			temp.put("state",Integer.parseInt(deliveryStats)+1);
			    		}
			    		temp.put("source","20");
			    		temp.put("number",findNum);
			    		temp.put("exc_id",findExpType);
			    		temp.put("data", json.toString().replace("&nbsp;"," "));
			    		temp.put("update_by",user.getUser_id());
			    		ordersService.insertExpTrackInfo(temp);
			    	}
				}
			}
			Page page = ordersService.getLogisticsInfo(parm, Integer.parseInt(pageNum), Integer.parseInt(pageSize));
			Map<String, Object> temp = new HashMap<String, Object>();
			temp.put("total", page.getTotalCount());
			temp.put("rows", page.getResult());
			expTracInfo = temp;
		}
		return SUCCESS;
	}
	
	
	private JSONObject expInfo;
	// 第一份 阿里物流API接口
	//	private static final String host = "http://jisukdcx.market.alicloudapi.com";
	//	private static final String path = "/express/query";
	//	private static final String method = "GET";
	//	private static final String appcode = "e8feb2acc90048e792e951eaff2dd9cf";
	//	private final String expNum = "number";
	
	
	// 第二份API接口 官网地址：https://market.aliyun.com/products/56928004/cmapi021863.html
	private final String host = "https://wuliu.market.alicloudapi.com";
	private final String path = "/kdi";
	private final String method = "GET";
	private final String appcode = "e8feb2acc90048e792e951eaff2dd9cf";
	private final String expNum = "no";
	
	/** 
	 *  请求阿里api
	 *  查询单个订单 当前物流情况
	 */
	public String getExpressInfo(){//获取快递信息
		HttpServletRequest request =ServletActionContext.getRequest();//获取单号和类型
		String number = request.getParameter("number");
		String type = request.getParameter("type");
		if(number!=null && type!=null){//判断单号不为空
		    Map<String, String> headers = new HashMap<String, String>();
		    //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
		    headers.put("Authorization", "APPCODE " + appcode);
		    Map<String, String> querys = new HashMap<String, String>();
		    querys.put(expNum, number);// 接口1的参数 number
		    querys.put("type", type);
		    try{
		    	HttpResponse response = CusHttpUtils.doGet(host, path, method, headers, querys);
		    	expInfo = JSONObject.fromObject(EntityUtils.toString(response.getEntity()));
		    }catch(Exception e){
		    	JSONObject json = new JSONObject();
				json.put("status", "1");
				json.put("msg",e.getMessage());
				expInfo = json;
		    }
		}else{
			JSONObject json = new JSONObject();
			json.put("status", "1");
			json.put("msg","no");
			expInfo = json;
		}
		return SUCCESS;
	}
	

	/**
	 * 以下是生成的 Set和Get方法
	 */
	public Map<String, Object> getExpTracInfo() {
		return expTracInfo;
	}
	public void setExpTracInfo(Map<String, Object> expTracInfo) {
		this.expTracInfo = expTracInfo;
	}
	public String getFindNum() {
		return findNum;
	}
	public void setFindNum(String findNum) {
		this.findNum = findNum;
	}
	public String getFindExpType() {
		return findExpType;
	}
	public void setFindExpType(String findExpType) {
		this.findExpType = findExpType;
	}
	public String getFindExpState() {
		return findExpState;
	}
	public void setFindExpState(String findExpState) {
		this.findExpState = findExpState;
	}
	public JSONObject getExpInfo() {
		return expInfo;
	}
	public void setExpInfo(JSONObject expInfo) {
		this.expInfo = expInfo;
	}
	private String Null2Str(Object in){
		return (in==null)?"":String.valueOf(in);
	}
	public OrdersService getOrdersService() {
		return ordersService;
	}
	public void setOrdersService(OrdersService ordersService) {
		this.ordersService = ordersService;
	}

	public HashMap<String, Object> getOrdersMapResult() {
		return ordersMapResult;
	}

	public void setOrdersMapResult(HashMap<String, Object> ordersMapResult) {
		this.ordersMapResult = ordersMapResult;
	}

	public HashMap<String, Object> getDetailsMapResult() {
		return detailsMapResult;
	}

	public void setDetailsMapResult(HashMap<String, Object> detailsMapResult) {
		this.detailsMapResult = detailsMapResult;
	}

	public List<OrderInfoDto> getOrdersInfoList() {
		return ordersInfoList;
	}

	public void setOrdersInfoList(List<OrderInfoDto> ordersInfoList) {
		this.ordersInfoList = ordersInfoList;
	}

	public List<OrderDetailInfoDto> getDetailsInfoList() {
		return detailsInfoList;
	}

	public void setDetailsInfoList(List<OrderDetailInfoDto> detailsInfoList) {
		this.detailsInfoList = detailsInfoList;
	}

	public OrderInfoDto getOrderInfo() {
		return orderInfo;
	}

	public void setOrderInfo(OrderInfoDto orderInfo) {
		this.orderInfo = orderInfo;
	}

	public OrderDetailInfoDto getDetailInfo() {
		return detailInfo;
	}

	public void setDetailInfo(OrderDetailInfoDto detailInfo) {
		this.detailInfo = detailInfo;
	}

	public String getOrderId() {
		return orderId;
	}

	public void setOrderId(String orderId) {
		this.orderId = orderId;
	}

	public String getDetailId() {
		return detailId;
	}

	public void setDetailId(String detailId) {
		this.detailId = detailId;
	}

	public String getFindPubFlg() {
		return findPubFlg;
	}

	public void setFindPubFlg(String findPubFlg) {
		this.findPubFlg = findPubFlg;
	}

	public String getFindOrderId() {
		return findOrderId;
	}

	public void setFindOrderId(String findOrderId) {
		this.findOrderId = findOrderId;
	}

	public String getFindOrderNo() {
		return findOrderNo;
	}

	public void setFindOrderNo(String findOrderNo) {
		this.findOrderNo = findOrderNo;
	}

	public String getFindType() {
		return findType;
	}

	public void setFindType(String findType) {
		this.findType = findType;
	}

	public String getFindState() {
		return findState;
	}

	public void setFindState(String findState) {
		this.findState = findState;
	}

	public String getFindPartner() {
		return findPartner;
	}

	public void setFindPartner(String findPartner) {
		this.findPartner = findPartner;
	}

	public String getFindDateStart() {
		return findDateStart;
	}

	public void setFindDateStart(String findDateStart) {
		this.findDateStart = findDateStart;
	}

	public String getFindDateEnd() {
		return findDateEnd;
	}

	public void setFindDateEnd(String findDateEnd) {
		this.findDateEnd = findDateEnd;
	}

	public String getOrder() {
		return order;
	}

	public void setOrder(String order) {
		this.order = order;
	}

	public String getIds() {
		return ids;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}

	public String getFindPayPf() {
		return findPayPf;
	}

	public void setFindPayPf(String findPayPf) {
		this.findPayPf = findPayPf;
	}

	public List<PartnerInfoDto> getPartnerComboList() {
		return partnerComboList;
	}

	public void setPartnerComboList(List<PartnerInfoDto> partnerComboList) {
		this.partnerComboList = partnerComboList;
	}

	public StateHisInfoDto getStateHisInfo() {
		return stateHisInfo;
	}

	public void setStateHisInfo(StateHisInfoDto stateHisInfo) {
		this.stateHisInfo = stateHisInfo;
	}

	public String getPrintImgsInfo() {
		return printImgsInfo;
	}

	public void setPrintImgsInfo(String printImgsInfo) {
		this.printImgsInfo = printImgsInfo;
	}

	public String getFindInvId() {
		return findInvId;
	}

	public void setFindInvId(String findInvId) {
		this.findInvId = findInvId;
	}

	public String getFindMobile() {
		return findMobile;
	}

	public void setFindMobile(String findMobile) {
		this.findMobile = findMobile;
	}

	public String getFindPayOrderNo() {
		return findPayOrderNo;
	}

	public void setFindPayOrderNo(String findPayOrderNo) {
		this.findPayOrderNo = findPayOrderNo;
	}

	public String getWithBleed() {
		return withBleed;
	}

	public void setWithBleed(String withBleed) {
		this.withBleed = withBleed;
	}

	public String getZoom() {
		return zoom;
	}

	public void setZoom(String zoom) {
		this.zoom = zoom;
	}
	public List<ExpressComInfoDto> getListExpC() {
		return listExpC;
	}
	public void setListExpC(List<ExpressComInfoDto> listExpC) {
		this.listExpC = listExpC;
	}

	public String getFindUserId() {
		return findUserId;
	}
	public void setFindUserId(String findUserId) {
		this.findUserId = findUserId;
	}
}
